<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <!-- 具名插槽 -->
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" :disabled="!checkPermission('import')" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" sortable="" :formatter="formatEmployment" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template slot-scope="obj">
              {{
                obj.row.timeOfEntry | formatDate
              }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"

                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="changeRole(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('delete')" @click="delEmploye(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" />
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 角色分配权限 -->
      <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>
<script>
import { getEmployeeList, delEmployeeList } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import addEmployee from '@/views/employees/components/add-employee'
import assignRole from '@/views/employees/components/assign-role'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'

export default {
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      userId: '',
      showRoleDialog: false, // 控制展示角色弹层
      showCodeDialog: false, // 控制二维码弹层
      list: [], // 表格数据
      page: {
        page: 1,
        total: 0,
        size: 10
      },
      loading: false,
      showDialog: false
    }
  },
  created() {
    this.getEmploye()
  },
  methods: {
    async getEmploye() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    changePage(newPage) { // 分页
      this.page.page = newPage
      this.getEmploye()
    },
    async delEmploye(id) { // 删除员工个人信息
      try {
        await this.$confirm('确认删除员工信息吗？')
        await delEmployeeList(id)
        this.getEmploye() // 更新视图
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }
    },
    exportData() { // 导出员工信息表
      const header = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => { // 按需导入
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total }) // 获取所有数据
        const data = this.formatJson(header, rows) // 将数组转换为用户需要的格式
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(header), // 导出数据的表头
          data, // 导出的具体数据
          filename: '员工薪资表', // 导出表的名称
          autoWidth: true, // 单元格是否要自适应宽度
          bookType: 'csv', // 导出文件的文本类型
          multiHeader, // 设置表头信息
          merges
        })
      })
    },
    formatJson(header, rows) { // 将数组进行转换
      return rows.map(item => {
        // item是对象  => 转化成只有值的数组 => 数组值的顺序依赖headers  {username: '张三'  }
        // Object.keys(headers)  => ["姓名", "手机号",...]
        return Object.keys(header).map(key => { // key为["姓名", "手机号",...] 的某一项
          if (header[key] === 'timeOfEntry' || header[key] === 'correctionTime') { // 如果为时间格式进行转换
            return formatDate(item[header[key]]) // 返回处理好的时间格式
          } else if (header[key] === 'formOfEmployment') {
            const res = EmployeeEnum.hireType.find(obj => obj.id === item[header[key]])
            return res ? res.value : '未知'
          }
          return item[header[key]]
        }) // /  得到 ['张三'，'129'，'dd','dd']
      })
    },
    showQrCode(url) { // 二维码展示处理
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('用户还未上传头像')
      }
    },
    formatEmployment(row, column, cellValue, index) { // 枚举数据转换
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async changeRole(id) { // 角色分配权限
      this.userId = id // props传值 是异步的
      // 异步函数
      await this.$refs.assignRole.getUserInfo(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
